package com.umfwechat.lightprogram.controller.my;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.ReqMessage;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.lightprogram.vo.SalesmanStatusVo;
import com.umfwechat.util.DESCrypt;
import com.umfwechat.util.DesUtil;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.WexinQrCodeUtil;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AgentPerm;
import com.umpay.sp.model.saas.OperplatRel;
import com.umpay.sp.service.saas.remote.AgentPermServiceRemote;
import com.umpay.sp.service.saas.remote.OperPlatRelServiceRemot;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.util.StringUtil;

/**
 * 
 * @author xuhuibing 
 *
 */


@Controller
@RequestMapping("/agentManagement")
public class SalesmanController {
	

	private static Logger logger = LoggerFactory.getLogger(SalesmanController.class);
	
	@Resource
	private OperPlatRelServiceRemot operPlatRelServiceRemot;
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;
	@Resource
	private AgentPermServiceRemote agentPermServiceRemote;
	
	/**
	 * 查询业务员列表 
	 * @param agentId
	 * @param pageNo
	 * @param pageSize
	 * @return 
	 * @throws Exception 
	 * @throws IllegalArgumentException 
	 */
	@RequestMapping(value="/salesmanList",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject salesmanList(HttpServletRequest request,HttpServletResponse response) throws Exception{
		JSONObject json = new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG,"查询列表成功");
		
		//收集客户端请求数据，
		String reqJSON = null;
		try {
			reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
			logger.info("【查詢业务员信息入参】" + reqJSON);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "查詢业务员信息获取失败");
			logger.error("【查詢业务员信息转换异常】");
			return json;
		}
		JSONObject param=JSONObject.fromObject(reqJSON);
		String agentId = param.optString(CommonConsts.LOGINAGENTID);	//loginAgentId 代理商编号	
		String pageNum = param.optString(CommonConsts.PAGE_NO);		//pageNo当前页 
		
		//收集参数：当前页
		if(StringUtil.isEmpty(pageNum)){
			pageNum="1";
		}
		//收集参数：每页条数
		String pageSize = param.optString(CommonConsts.PAGE_SIZE);//pageSize 每页条数
		if(StringUtil.isEmpty(pageSize)){
			pageSize="20";
		}
		Integer startNo = Integer.valueOf(pageSize)*(Integer.valueOf(pageNum)-1);//计算开始行数
		Integer endNo = Integer.valueOf(pageSize)*(Integer.valueOf(pageNum));//计算结束行数
		//组装设置请求参数
		ReqMessage reqMap = ReqMessageUtil.makeReq();
		Map<String,Object> validatParam = new HashMap<String,Object>();
		validatParam.put(CommonConsts.RPID, reqMap.getRpid());
		validatParam.put(CommonConsts.AGENTID, agentId);//代理商编号
		validatParam.put(CommonConsts.START_NO,startNo.toString());
		validatParam.put(CommonConsts.END_NO,endNo.toString());
		Map<String,Object> crmResult = null;//调用CRM
		try {
			logger.info("【调用CRM查询管理员基本信息接口】 开始 ");
			XStream xstream = new XStream(new DomDriver());
			logger.info("【调用CRM查询管理员基本信息接口】 输入参数:"+validatParam);
//			String url="http://10.10.77.76:7000/restUserManager/rest2/QueryAgentManager/QueryAgentManager.xml";
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentManager");
			crmResult = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, validatParam);
			logger.info("【调用CRM查询管理员基本信息接口】返回参数"+crmResult);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用crm查询管理员基本信息接口异常");
			logger.info("【调用cr查询管理员基本信息接口异常】");
			return json;
		}
		//判断他的返回结果是否为0000,resMap保存输入信息
		String retCodeRs = (String) crmResult.get("retCode");
		if(RetCode.SUCCESS.equals(retCodeRs)){
			//TODO 看集合返回 返回类型 获取管理员列表集合
			List<Map<String,Object>> agentManagerList = (List<Map<String,Object>>) crmResult.get("agentManagerList");
			//判断集合是否为空 
			if(agentManagerList==null){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "查询列表失败");
				logger.info("【查询业务员列表失败】");
				return json;
			}else{
				//遍历业务员集合（不含状态）
				List<SalesmanStatusVo> listVo  =new ArrayList<SalesmanStatusVo>();
				//遍历管理员列表
				for (Map<String, Object> map : agentManagerList) {
					//获取管理员信息
					SalesmanStatusVo salesmanStatusVo= new SalesmanStatusVo();
					String useridr=(String)map.get(CommonConsts.USERNAME);//业务员userid
					String state = (String)map.get("state");//保存业务员停用状态:停用改为4返回

					salesmanStatusVo.setUserId(useridr);
					salesmanStatusVo.setAgentId(agentId);
					com.umpay.sp.model.common.ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
					//设置查询业务员信息请求参数
					Map<String, String> map1 = reqMessage.getReqMap();
					map1.put(CommonConsts.AGENTID, agentId);//代理商编号
					map1.put(CommonConsts.USERID,useridr);//业务员名称
					map1.put(CommonConsts.STATE,ValueConsts.STATE_TWO);//state:"2" STATE 状态	SMALLINT 2-正常;4-注销
					ResMessage resMessage=null;
					try {
						//logger.info("======>>>>>获取外部用户信息关系接口 请求入参:" +reqMessage);
						resMessage = operPlatRelServiceRemot.getOperPlatRels(reqMessage);
						//logger.info("======>>>>>>获取外部用户关系接口 返回参数: " + resMessage);
					} catch (Exception e) {
						json.put(CommonConsts.RETCODE, "0001");
						json.put(CommonConsts.RETMSG, "调用查询外部用户关系接口失败");
						logger.info("【调用查询外部用户关系接口 异常】");
						return json;
					}
					String retCode = resMessage.getRetCode();
					//判断查询外部用户关系接口返回是否成功,0000为成功
					if(RetCode.SUCCESS.equals(retCode)){
						Map<String, Object> map2 = resMessage.getResMap();
						//获取外部用户类信息
						List<OperplatRel> list2=(List<OperplatRel>)map2.get("operPlatRels");
						//设置状态salesmanStatus:0为没有扫码,1为扫码
						salesmanStatusVo.setSalesmanStatus(ValueConsts.OPER_TYPE);
						if(list2 !=null && !list2.isEmpty()){ 
							for (OperplatRel operPlatRel : list2) {
								//获取外部用户IdExternaluserid,查看是否绑定过
								String openid=operPlatRel.getExternaluserid();
								
								if(!"".equals(StringUtil.trim(openid))){ 
									salesmanStatusVo.setSalesmanStatus(ValueConsts.OPER_TYPE_ONE);
								}
							}
						} 
						if(RetCode.FAIL.equals(state)){
							salesmanStatusVo.setSalesmanStatus("4");
						}
						listVo.add(salesmanStatusVo);
					
					}else{
						json.put(CommonConsts.RETCODE, "0001");
						json.put(CommonConsts.RETMSG, "查询业务员列表信息失败");
						logger.info("【查询业务员列表信息失败】");
						return json;
					}
				}
				json.put("salesmanList", listVo);
				return json;
			}
		}else{
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "查询业务员列表失败");
			logger.info("【查询业务员列表失败】");
			return json;
		}
	}

	/**
	 * 个人信息维护：密码修改
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/salesmanMessModifiy",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject salesmanMessModifiy(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		JSONObject json = new JSONObject();
		String reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e1) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "请求数据转换异常");
			logger.info("【请求数据转换异常】");
			return json;
		}
		String agentId = param.optString(CommonConsts.LOGINAGENTID);	//代理商编号
		String xinPassword = param.optString("password");	//新密码
		String assistId = param.optString(CommonConsts.LOGINASSISTID);	//代理商的账号
		String userId = param.optString(CommonConsts.LOGINUSERID);	//
		String str = RedisUtil.get(CacheConsts.LOGIN+agentId+userId);//
		if(str == null){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "数据转换异常");
			return json;
		}
		String[] values = str.split(",");
		String jiuPassword = values[2];//缓存中的旧密码是明文需要加密
		String token = values[3];//TODO token保存?
		//加密请求
		DESCrypt desCrypt = new DESCrypt();//encrypt
		String newPassword = null;
		String oldPassword = null;
		try {
			newPassword = desCrypt.encrypt(xinPassword);
		} catch (Exception e1) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "新密码加密异常");
			logger.info("【新密码加密异常】");
			return json;
		}
		try {
			oldPassword = desCrypt.encrypt(jiuPassword);
		} catch (Exception e1) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "旧密码加密异常");
			logger.info("【旧密码加密异常】");
			return json;
		}
		//组装请求参数 修改用户密码
		Map<String,Object> validatParam = new HashMap<String, Object>();
		ReqMessage reqMessage = ReqMessageUtil.makeReq();
		validatParam.put(CommonConsts.RPID, reqMessage.getRpid());
		validatParam.put(CommonConsts.USERNAME, userId);//userid
		validatParam.put(CommonConsts.AGENTID, agentId);//agentId
		validatParam.put("id", assistId);//assistid
		validatParam.put("oldPassword",oldPassword);//旧密码
		validatParam.put("newPassword",newPassword);//新密码
		if("admin".equals(userId)){
			validatParam.put("managerType", ValueConsts.ZERO);//管理员类型manager:0:admin,1:普通业务员
		}else{
			validatParam.put("managerType", ValueConsts.PAGE_ONE);
		}
		//p2接口是Map类型	
		Map<String,Object> crmResult = null;
		logger.info("【调用修改用户密码接口开始 】");
		try {
			logger.info("【调用CRM修改密码接口】入参："+validatParam);
			XStream xstream = new XStream(new DomDriver());
//			String url="http://10.10.77.76:7000/restUserManager/rest2/UpdateAgentManagerLoginPassword/UpdateAgentManagerLoginPassword.xml";
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.updateLoginPwd");
			crmResult = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, validatParam);
			logger.info("【调用CRM修改密码接口】出参："+crmResult);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用crm修改密码接口异常");
			logger.info("【调用crm修改密码接口异常】");
			return json;
		}
		String retCode = (String) crmResult.get("retCode");
		//TODO
		if("00060528".equals(retCode)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "新密码与旧密码不能相同");
			logger.info("【新密码与旧密码不能相同】");
			return json;
		}
		//判断返回结果是否为0000,否则修改结果返回异常
		if(!RetCode.SUCCESS.equals(retCode)){	
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "更新个人信息失败！");
			logger.info("【更新个人信息失败】");
			return json;
		}
		RedisUtil.set(CacheConsts.LOGIN+agentId+userId, ValueConsts.THIRTY_DAY, userId+","+assistId+","+xinPassword+","+token);
//		logger.info("【个人信息维护】缓存中key = "+CacheConsts.LOGIN+agentId+userId+"缓存中value为"+ userId+","+assistId+","+xinPassword+","+token);
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG,"更新个人信息成功");
		return json;
	}
	
	/**
	 * 删除业务员 
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value="/salesmanStateModifiy",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject salesmanStateModifiy(HttpServletRequest request,HttpServletResponse response){
		
		JSONObject json = new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG,"刪除业务员信息成功");
		
		//收集客户端请求数据
		String reqJSON = null;
		
		reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);//_requestData
		
		JSONObject param=JSONObject.fromObject(reqJSON);
		String agentId = param.optString(CommonConsts.LOGINAGENTID);//代理商编号
		String salesmanId = param.optString(CommonConsts.USERID);	//userId用户编号
		
		com.umpay.sp.model.common.ReqMessage req = ReqMessageUtil.makeSpReq();
		req.put(CommonConsts.AGENTID, agentId);//代理商编号
		req.put(CommonConsts.SALESMANID, salesmanId);//salesmanId业务员编号
		com.umpay.sp.model.common.ResMessage res=null;
		try {
			logger.info("【删除业务员信息】请求参数: " + req);
			res = storeInfServiceRemote.updateSalesmanIdByAgentIdAndSalesmanId(req);
			logger.info("【删除业务员信息 】返回参数: " + res);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用删除接口失败，请稍后再试");
			logger.info("【调用删除业务员接口异常】 " );
			return json;
		}
		//判断返回码是否为0000
		String retCode = res.getRetCode();

		if(!RetCode.SUCCESS.equals(retCode)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "删除业务员信息失败");
			logger.info("【删除业务员信息失败】");

			return json;
		}
		return json;
	}
	
	
	/**
	 * 生成二维码信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/getwxacode",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject getwxacode(HttpServletRequest request,HttpServletResponse response){
	
		JSONObject json = new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG,"生成二维码信息成功");
		//收集客户端请求数据
		String reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null; 
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put("retMsg", "请求参数不足");
			logger.info("【请求数据转换异常】");
			return json;
		}
		String agentId = param.optString("loginAgentId");//代理商编号
		String userid = param.optString("userId");	//用户名
		String assistId = param.optString("loginAssistId");//账号
		
		//调用生成业务员二维码的流程，组成json返回二维码的qrURL
		WexinQrCodeUtil util = new WexinQrCodeUtil();
    	//获取token
		String tokenR =  util.reqToken();
    	JSONObject object = JSONObject.fromObject(tokenR);
    	String token = object.optString(CommonConsts.ACCESS_TOKEN_XCX);//access_token
    	//获取UUID
    	String uuid = UUID.randomUUID().toString();
    	//设置token时长
    	String rValue = userid + "|" +agentId+ "|" + assistId;
    	RedisUtil.set(uuid, 60*60*24*1000, rValue);
  //  	String loginToken = RedisUtil.get(uuid);
    	//设置跳转页面
    	String weixinQrPath = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties", "weixin.qr.path", "");
    	logger.info("【设置跳转页面path】" + weixinQrPath);
    	//二维码参数
    	String path = weixinQrPath+"?loginToken="+uuid;
    	logger.info("【二维码信息参数】二维码信息:" + path);
    	//获取二维码路径
    	String url =  util.getwxacode(path, token);
    	//获取图片服务器Http地址
    	String imgHttpUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","img.http.url", "");	
    	logger.info("【获取图片服务器地址】" + imgHttpUrl + url);
    	//拼接二维码路径,返回前端
    	json.put("qrUrl", imgHttpUrl + url);
		
    	return json;
	}
	
	/**
	 * 停用业务员
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/salesmanDown")
	@ResponseBody
	public JSONObject salesmanDown(HttpServletRequest request,HttpServletResponse response){
		
		JSONObject json = new JSONObject();
		String reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "请求数据转换异常");
			logger.info("请求数据转换异常");
			return json;
		}
		Map<String,Object> validatParam = new HashMap<String,Object>();//账号:id,assistId:b,cesha.SAAS.用户名:userName:xiaohei
		String agentId = param.optString(CommonConsts.LOGINAGENTID);
		String assistId = param.optString(CommonConsts.LOGINASSISTID);//账号:assistId:b:ceshia:gaigaia
		String userId = param.optString(CommonConsts.USERID);//业务员名称
		String salesmanStatus = param.optString("salesmanStatus");
		
		Map<String, Object> req = ReqMessageUtil.makeReqMap();
		validatParam.put(CommonConsts.RPID,req.get(CommonConsts.RPID));
		validatParam.put(CommonConsts.AGENTID, agentId);//代理商编号
		validatParam.put("id", assistId);//账号:assistId:b:ceshia
		validatParam.put(CommonConsts.USERNAME, userId);//用户名:userId:userName:admin:test1
		validatParam.put(CommonConsts.STATE, salesmanStatus);//业务员状态0-停用,1-启用
		validatParam.put("managerType", ValueConsts.STATE_ONE);//管理员类别:0:admin,1:普通操作员
		//
		Map<String,Object> crmResult = null;//调用CRM
		try {
			logger.info("【调用CRM停用业务员接口】 开始 ");
			XStream xstream = new XStream(new DomDriver());
			logger.info("【调用CRM停用业务员接口】 输入参数:"+validatParam);
//			String url="http://10.10.77.76:7000/restUserManager/rest2/UpdateAgentManagerState/UpdateAgentManagerState.xml";
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.salwsmanDown");
			crmResult = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, validatParam);
			logger.info("【调用CRM停用业务员接口】返回参数"+crmResult);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用crm停用业务员接口异常");
			logger.info("【调用crm停用业务员接口异常】");
			return json;
		}
		String retCode = (String) crmResult.get("retCode");
		if(!RetCode.SUCCESS.equals(retCode)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "停用业务员失败");
			logger.info("【停用业务员操作失败】");
			return json;
		}

		//保存到Redis业务员的停用/启用状态
		if("0".equals(salesmanStatus)){
			RedisUtil.set(CacheConsts.ISFORBIDDEN+agentId+userId, ValueConsts.THIRTY_DAY, salesmanStatus);
		}else{
			RedisUtil.del(CacheConsts.ISFORBIDDEN+agentId+userId);
		}
		logger.info("【缓存中业务员禁用状态】key值:"+CacheConsts.ISFORBIDDEN+agentId+userId+"value值:"+salesmanStatus);
		json.put("salesmanStatus", salesmanStatus);
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "业务员信息操作成功");
		return json;
		
	}
	
	/**
	 * 更新登录密码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateLoginPwd")
	@ResponseBody
	public JSONObject updateLoginPwd(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		String reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param =	JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "数据转换异常");
			return json;
		}
		String agentId = param.optString("loginAgentId");	//代理商编号
		String assistId = param.optString("loginAssistId");	//代理商的账号assistId:id:b:ceshia
		String userId = param.optString("loginUserId");		//用户名:userId:admin
		String xinPassword = param.optString("password");	//要修改的密码
		String jiuPassword = ValueConsts.LOGIN_PASSWD;//"111111";
		String str = RedisUtil.get(CacheConsts.LOGIN+agentId+userId);
		if(str == null){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "数据转换异常");
			return json;
		}
		String[] values = str.split(",");
		String loginToken = values[3];
		//更新登录新密码DES加密
		String newPassword =null;
		String oldPassword =null;
		DESCrypt desCrypt = new DESCrypt();
		try {
			newPassword = desCrypt.encrypt(xinPassword);
		} catch (Exception e2) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "密码加密异常");
			logger.info("【新密码加密异常】");
			return json;
		} 
		try {
			oldPassword = desCrypt.encrypt(jiuPassword);
		} catch (Exception e3) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "密码加密异常");
			logger.info("【旧密码加密异常】");
			return json;
		}
		//组装请求信息
		Map<String,Object> validatParam = new HashMap<String,Object>();
		com.umfwechat.common.ReqMessage reqMessage = ReqMessageUtil.makeReq();
		validatParam.put(CommonConsts.RPID, reqMessage.getRpid());
		validatParam.put("id", assistId);//账号
		validatParam.put(CommonConsts.AGENTID, agentId);//代理商编号
		validatParam.put(CommonConsts.USERNAME, userId);
		validatParam.put("newPassword", newPassword);//新密码
		validatParam.put("oldPassword", oldPassword);//老密码
		if("admin".equals(userId)){
			validatParam.put("managerType", ValueConsts.ZERO);//管理员类型manager:0:admin,1:普通业务员
		}else{
			validatParam.put("managerType", ValueConsts.PAGE_ONE);
		}
		//调用crm接口
		Map<String,Object> crmResult = null;
		try {
			logger.info("【调用CRM修改登录密码接口】入参："+validatParam);
			XStream xstream = new XStream(new DomDriver());
//			String url="http://10.10.77.76:7000/restUserManager/rest2/UpdateAgentManagerLoginPassword/UpdateAgentManagerLoginPassword.xml";
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.updateLoginPwd");
			crmResult = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, validatParam);
			logger.info("【调用CRM修改登录密码接口】出参："+crmResult);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用crm修改登录密码接口异常");
			logger.info("【调用crm修改登录密码接口异常】");
			return json;
		}
		String retCode = (String) crmResult.get(CommonConsts.RETCODE);
		if("00060528".equals(retCode)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "新密码与旧密码不能相同");
			logger.info("【新密码与旧密码不能相同】");
			return json;
		}
		if(!RetCode.SUCCESS.equals(retCode)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "修改登录密码失败");
			logger.info("【修改登录密码失败】");
			return json;
		}
		
		RedisUtil.set(CacheConsts.LOGIN+agentId+userId, ValueConsts.THIRTY_DAY, userId+","+assistId+","+xinPassword+","+loginToken);
//		logger.info("【首次登录修改密码】缓存中key = "+CacheConsts.LOGIN+agentId+userId+"缓存中value为"+ userId+","+assistId+","+xinPassword+","+loginToken);
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "修改登录密码成功");
		return json;
	}
	/**
	 * 保存管理员信息及权限控制 crm
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value="/salesmanAdd",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject salesmanAdd(HttpServletRequest req, HttpServletResponse resp){
		
		JSONObject json = new JSONObject();
		String reqJSON = (String) req.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "请求数据转换异常");
			return json;
		}
		String permissionConf = param.optString("permissionConf");
		String operator = param.optString(CommonConsts.LOGINUSERID);
		String id = param.optString(CommonConsts.LOGINASSISTID);//账号
		String agentId = param.optString(CommonConsts.LOGINAGENTID);//代理商编号
		String userName = param.optString(CommonConsts.USERID);//loginUserId用户名:userId:admin:ceshia//代理商的账号assistId:id:b:ceshia
		if(CommonConsts.ADMIN.equals(userName)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "业务员名称不能为admin");
			return json;
		}
		Map<String,Object> validatParam =new HashMap<String,Object>();
		ReqMessage reqMessage = ReqMessageUtil.makeReq();
		validatParam.put(CommonConsts.RPID, reqMessage.getRpid());
		validatParam.put(CommonConsts.AGENTID, agentId);
		validatParam.put(CommonConsts.USERNAME, userName);
		validatParam.put("id", id);
		validatParam.put("managerType", ValueConsts.STATE_ONE);
//		validatParam.put("mobileId", "18899996666");
//		validatParam.put("email", "wangquan@.com");
		//保存管理员信息
		Map<String,Object> crmResult1 = null;
		try {
			logger.info("【调用CRM保存管理员接口】入参："+validatParam);
			XStream xstream = new XStream(new DomDriver());
//			String url="http://10.10.77.76:7000/restUserManager/rest2/CreateAgentManager/CreateAgentManager.xml";
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.createAgentManager");
			crmResult1 = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, validatParam);
			logger.info("【调用CRM保存管理员接口】出参："+crmResult1);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用crm保存管理员接口异常");
			logger.info("【调用crm保存管理员接口异常】");
			return json;
		}
		String retCode1 = (String) crmResult1.get("retCode");
		//00060507:该普通操作员已存在
		if("00060507".equals(retCode1)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "业务员名称已存在,请重新输入");
			logger.info("【业务员名称已存在,请重新输入】");
			return json;
		}
		if(!RetCode.SUCCESS.equals(retCode1)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "保存业务员信息失败");
			return json;
		}
		//------------------------------------保存业务员权限--------------------------------------------
		com.umpay.sp.model.common.ReqMessage paramMap = ReqMessageUtil.makeSpReq();
		String userId = param.optString(CommonConsts.USERID);
		String assistId = param.optString(CommonConsts.LOGINASSISTID);
		//配置权限状态0:默认关闭 1:开启
		String[] values = permissionConf.split(",");
		paramMap.put("searchStorePerm", "0");
		paramMap.put("searchProfitPerm", "0");
		paramMap.put("fetchBillDocPerm", "0");
		for(int i =0; i<values.length; i++){
			String a = values[i];
			if(a.contains("searchStorePerm")){
				paramMap.put("searchStorePerm","1");
			}
			if(a.contains("searchProfitPerm")){
				paramMap.put("searchProfitPerm", "1");
			}
			if(a.contains("fetchBillDocPerm")){
				paramMap.put("fetchBillDocPerm", "1");
			}
		}
		paramMap.put(CommonConsts.ASSISTID, assistId);
		paramMap.put(CommonConsts.SALESMANID, userId);
		paramMap.put(CommonConsts.AGENTID,agentId);
		paramMap.put("operator",operator);
		com.umpay.sp.model.common.ResMessage permResult = null;
		try {
			logger.info("【调用保存管理员权限配置接口】入参："+paramMap);
			permResult = agentPermServiceRemote.insertAgentPerm(paramMap);
			logger.info("【调用保存管理员权限配置接口】出参："+permResult);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "保存业务员权限信息失败");
			logger.info("【调用crm保存管理员接口异常】");
			return json;
		}
		String retCode = (String) permResult.getRetCode();
		if(!RetCode.SUCCESS.equals(retCode)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "保存业务员权限信息失败");
			return json;
		}
		
		//调用生成业务员二维码的流程，组成json返回二维码的qrURL
		WexinQrCodeUtil util = new WexinQrCodeUtil();
    	//获取token
		String tokenR =  util.reqToken();
    	JSONObject object = JSONObject.fromObject(tokenR);
    	//截取token值
    	String token = object.optString(CommonConsts.ACCESS_TOKEN_XCX);//access_token
    	//获取UUID
    	String uuid = UUID.randomUUID().toString();
    	//设置token时长
    	String rValue = userName + "|" +agentId+ "|" + assistId;
    	//有效期一天
    	RedisUtil.set(uuid, ValueConsts.THIRTY_DAY, rValue);
  //  	String loginToken = RedisUtil.get(uuid);
    	//设置跳转页面
    	String weixinQrPath = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties", "weixin.qr.path", "");
    	logger.info("【设置跳转页面的path为】" + weixinQrPath);
    	//二维码参数
    	String path = weixinQrPath+"?loginToken="+uuid;
    	logger.info("【二维码信息参数】" + path);
    	//获取二维码路径
    	String url =  util.getwxacode(path, token);
    	//获取图片服务器Http地址
    	String imgHttpUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","img.http.url", "");	
    	logger.info("【获取图片服务器地址】" + imgHttpUrl + url);
    	//拼接二维码路径,返回前端
    	json.put("qrUrl", imgHttpUrl + url);
    	//把权限存在缓存中,
		RedisUtil.set(CacheConsts.PERMISSIONCONF+agentId+userId, ValueConsts.THIRTY_DAY, permissionConf);
		logger.info("设置：缓存中key为："+CacheConsts.LOGIN+agentId+"缓存中value为"+permissionConf);
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "保存管理员信息成功");
		logger.info("【保存管理员信息成功】");
		return json;
	}
	

	/**
	 * 查询管理员权限配置
	 * @param req
	 * @param resp
	 * @return
	 */						
	@RequestMapping(value="/querySalesmanLimitConfig",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject querySalesmanLimitConfig(HttpServletRequest req, HttpServletResponse resp){
		 JSONObject json = new JSONObject();
		 String reqJSON = (String) req.getAttribute(CommonConsts.REQUESTDATA);
		 JSONObject param = null;
		 try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "请求数据转换异常");
			return json;
		}
//		 String salesmanId = param.optString(CommonConsts.LOGINUSERID);//业务员编号
		 String salesmanId = param.optString(CommonConsts.USERID);
		 String agentId = param.optString(CommonConsts.LOGINAGENTID);//代理商编号
		 String assistId = param.optString(CommonConsts.LOGINASSISTID);//账号
		 com.umpay.sp.model.common.ReqMessage reqMess = ReqMessageUtil.makeSpReq();
		 reqMess.put(CommonConsts.SALESMANID, salesmanId);
		 reqMess.put(CommonConsts.AGENTID,agentId);
		 reqMess.put(CommonConsts.ASSISTID,assistId);
		 ResMessage res = null;
		 try {
			logger.info("【获取代理商权限控制接口】输入参数：" + reqMess);
			res = agentPermServiceRemote.getAgentPermByPri(reqMess);
			logger.info("【获取代理商权限控制接口】输出参数：" + res);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "【获取代理商权限控制接口异常】");
			return json;
		}
		String retCode = res.getRetCode();
		if (!RetCode.SUCCESS.equals(retCode)) {
			// 从集合中获取权限控制参数,返回给前端
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "查询权限权限失败,请稍后再试");
			return json;
		}
		AgentPerm agentPerm = (AgentPerm) res.getResMap().get("agentPerm");
		if (agentPerm == null) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "服务器异常,请稍后再试");
			return json;
		}
		String searchProfitPerm = agentPerm.getSearchProfitPerm();
		String searchStorePerm = agentPerm.getSearchStorePerm();
		String fetchBillDocPerm = agentPerm.getFetchBillDocPerm();
		List<String> sp = new ArrayList<String>();
		if("1".equals(searchStorePerm)){
			sp.add("searchStorePerm");
		}
		if("1".equals(fetchBillDocPerm)){
			sp.add("fetchBillDocPerm");
		}
		if("1".equals(searchProfitPerm)){
			sp.add("searchProfitPerm");
		}
		json.put("permissionConf", sp);
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "查询权限成功");
		return json;
	}
	/**
	 * 更新管理员权限配置
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value="/updateSalesmanLimitConfig",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject updateSalesmanLimitConfig(HttpServletRequest req, HttpServletResponse resp){
		 JSONObject json = new JSONObject();
		 String reqJSON = (String) req.getAttribute(CommonConsts.REQUESTDATA);
		 JSONObject param = null;
		 try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "请求数据转换异常");
			return json;
		}
		 com.umpay.sp.model.common.ReqMessage reqMess = ReqMessageUtil.makeSpReq();
		 String userId = param.optString(CommonConsts.USERID);
		 String agentId = param.optString(CommonConsts.LOGINAGENTID);//代理商编号
		 String assistId = param.optString(CommonConsts.LOGINASSISTID);//账号
		 String operator = param.optString(CommonConsts.LOGINUSERID);
		 String permissionConf = param.optString("permissionConf");
		 if(permissionConf.contains("searchStorePerm")){
			 reqMess.put("searchStorePerm","1");
		 }else{
			 reqMess.put("searchStorePerm","0");
		 }
		 if(permissionConf.contains("searchProfitPerm")){
			 reqMess.put("searchProfitPerm","1");
		 }else{
			 reqMess.put("searchProfitPerm","0");
		 }
		 if(permissionConf.contains("fetchBillDocPerm")){
			 reqMess.put("fetchBillDocPerm","1");
		 }else{
			 reqMess.put("fetchBillDocPerm","0");
		 }
		 reqMess.put(CommonConsts.SALESMANID, userId);
		 reqMess.put(CommonConsts.AGENTID,agentId);
		 reqMess.put(CommonConsts.ASSISTID,assistId);
		 reqMess.put("operator",operator);
		 ResMessage resMess =null;
		try {
			logger.info("【更新代理商权限控制接口】输入参数：" + reqMess);
			resMess = agentPermServiceRemote.updateAgentPermByPri(reqMess);
			logger.info("【更新代理商权限控制接口】输出参数：" + resMess);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "【更新代理商权限控制接口异常】");
			return json;
		}
		String retCode = resMess.getRetCode();
		if (!RetCode.SUCCESS.equals(retCode)) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "【服务器异常,请稍后再试】");
			return json;
		}
		//获取登录中公共的权限参数
		RedisUtil.set(CacheConsts.PERMISSIONCONF+agentId+userId, ValueConsts.THIRTY_DAY, permissionConf);
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "【更新代理商权限信息成功】");
		return json;
	}
	
}